import { getToken, setToken, removeToken } from '@/utils/auth'
import { defineStore } from 'pinia'
import { login } from '@/api/user'
const useUserStore = defineStore('user', {
  state: () => ({
    token: getToken(),
    id: '',
    name: '',
    avatar: '',
    roles: [],
    permissions: [],
    info: {}
  }),
  actions: {
    // 登录
    login(userInfo: { name: string; password: string; code?: string }) {
      return new Promise<void>((resolve, reject) => {
        login(userInfo)
          .then(({ code, msg, data }: { code: number; msg: string; data: any }) => {
            if (code == 200) {
              setToken(data.token)
              this.token = data.token
              this.info = data
              this.id = data.id
              this.name = data.name
              this.avatar = data.avatar
              this.roles = data.role
              resolve()
            } else {
              reject(msg)
            }
          })
          .catch((error: any) => {
            reject(error)
          })
      })
    },
    // 获取用户信息
    getInfo() {
      return new Promise((resolve, reject) => {
        //设置用户信息 渲染后端路由
      })
    },
    // 退出系统
    logOut() {
      return new Promise((resolve, reject) => {
        // 退出登录
      })
    }
  }
})

export default useUserStore
